package com.zhangqiancheng.wcdmaconsole;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import Event.MyEvent;
import Event.MyEventListenerInterface;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ProtocalAndUdp.PackRezult;
import com.ProtocalAndUdp.PhoneEnvironment;
import com.ProtocalAndUdp.ReadWriteFile;
import com.ProtocalAndUdp.SendDatas;
import com.ProtocalAndUdp.UdpClientSocket;

public class SettingsActivity extends Activity {
	/************马浩**********************/
	MyEventListenerInterface lis=null;
	PackRezult revPack=null;
	String[] sResult=new String[2];
	
	//定义Handler对象
	private Handler handler =new Handler();
	private Runnable run=new Runnable() {
		@Override
		public void run() {
			updateUI();
		}
	};
	
	private void updateUI(){
		//处理接收数据
		if(revPack.getId().equals("0302")){
			sResult[0]=revPack.getContent();
		}
		else if(revPack.getId().equals("0615")){
			sResult[1] = revPack.getContent();
		}
		
		if (sResult[0] == null || sResult[1] == null)
			return;
			
		if(sResult[0].equals(sResult[1])&&sResult[1].equals("0")){
			//成功 to do...................
			Toast.makeText(getApplicationContext(), "参数已保存", Toast.LENGTH_SHORT).show();
			Log.d("setting", "参数已保存");
			sResult=new String[2];
			try {
				ReadWriteFile.writeTxtFile(this, "设备参数设置");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			onBackPressed();
		}
		else{
			//失败 to do...................
			Toast.makeText(getApplicationContext(), "参数设置失败", Toast.LENGTH_SHORT).show();
			sResult=new String[2];
			Log.d("setting", "参数设置失败");
		}
	}
	/************马浩**********************/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		/****马浩--接收设备数据*******************************/
		lis=new MyEventListenerInterface(){
			public void myEventOccurred(MyEvent event){
				Log.i("event",event.getRezult().getContent());
				revPack=event.getRezult();
				handler.post(run);
			}
		};
		try {
			UdpClientSocket.getClient().getRegister().addMyEventListener(lis);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		 
		/*************获取手机信号强度*****************/
        initSignal();
        getEnvironment();
    }

    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	try {
			UdpClientSocket.getClient().getRegister().removedMyEventListener(lis);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	super.onDestroy();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
    }
    
    public void okButtonClick(View view) throws Exception {
    	//发送设置参数
    	String content="";
    	
    	TextView tv0=(TextView)findViewById(R.id.etARFCN);
    	TextView tv1=(TextView)findViewById(R.id.etPSC);
    	TextView tv2=(TextView)findViewById(R.id.etGARF);
    	TextView tv3=(TextView)findViewById(R.id.etBSIC);
    	increcentLac();
    	
    	if(tv0.getText().length()!=0&&tv3.getText().length()!=0&&tv0.getText().length()!=0
    			&&tv2.getText().length()!=0&&tv3.getText().length()!=0){
    		content="MCC:460@MNC:01@LAC:"+lac +"@"+"ARFCNNo:"+tv0.getText().toString()+"@PSC:"+tv1.getText()+"@";
        	SendDatas.send("03", "01", content);
        	Log.d("setting","发送"+"0301"+content);
        	Thread.sleep(220);
        	
        	content=tv2.getText().toString()+"#"+tv3.getText()+"@";
        	SendDatas.send("06", "14", content);
        	Log.d("setting","发送"+"0614"+content);
    	}
    	else{
    		//提示需要输入提示为完成
    		AlertDialog.Builder builder = new Builder(this);
    		builder.setIcon(android.R.drawable.btn_star);
    		builder.setMessage("请将参数填写完整！");
    		builder.setTitle("警告");
    		builder.setPositiveButton("确认", new OnClickListener() {
    		    @Override
    		    public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    		    }
    		});
    		builder.create().show();
    	}
    }
    
    int lac=1000;
    private void increcentLac(){
    	if(lac<2000)
    		lac++;
    	else
    		lac=1000;
    }
   
    public void backButtonClick(View view) {
    	onBackPressed();
    }

    TelephonyManager        Tel;
    MyPhoneStateListener    MyListener;
    
    /**
     * 获取手机信号强度
     */
    private void initSignal() {
		MyListener   = new MyPhoneStateListener();
        Tel       = ( TelephonyManager )getSystemService(this.TELEPHONY_SERVICE);
        Tel.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
	}
    
    @Override
    protected void onPause()
    {
      super.onPause();
      Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);
   }
 
   @Override
   protected void onResume()
   {
      super.onResume();
      Tel.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
   }
   
    private class MyPhoneStateListener extends PhoneStateListener
    {
      @Override
      public void onSignalStrengthsChanged(SignalStrength signalStrength)
      {
         super.onSignalStrengthsChanged(signalStrength);
         //更改值
         TextView rssi= (TextView)findViewById(R.id.tvRSSI);
         rssi.setText(String.valueOf(signalStrength.getGsmSignalStrength()));
      }
    };
 
    /**
     * 获取Lac和CI和相邻小区ID
     */
    private void getEnvironment(){
    	int[] infor=new int[2];
    	infor=PhoneEnvironment.getLacAndCellId(SettingsActivity.this);
    	if(infor!=null){
	    	TextView ci=(TextView)findViewById(R.id.tvCI);
	    	ci.setText(infor[0]+" ");
	    	TextView lac=(TextView)findViewById(R.id.tvLAC);
	    	lac.setText(infor[1]+" ");
    	}
    	//获取相邻小区信息
    	int iCount=1;
    	LinearLayout cellsLine=(LinearLayout)findViewById(R.id.linearLayoutcells);
    	HashMap<String, String> cells= PhoneEnvironment.getNeigborCells(this);
//    	int size=cells.size();
//    	Toast.makeText(this, String.valueOf(size), Toast.LENGTH_SHORT)
//		.show();
    	Iterator<Entry<String, String>> iter = cells.entrySet().iterator();
    	while (iter.hasNext()) {
    		Entry<String, String> entry = iter.next();
    		Object val = entry.getValue();
    		//生成控件
    		TableRow tr=new TableRow(this);
    		
    		TextView view=new TextView(this);
    		view.setText("cell"+iCount);
    		tr.addView(view);
    		
    		TextView view1=new TextView(this);
    		view1.setText(val.toString());
    		tr.addView(view1);
    	
    		cellsLine.addView(tr);
    	}
    }
}
